<template>
  <div class="video-review-container">
    <div class="content-wrapper">
      <div class="review-card">
        <!-- 顶部导航和工具栏 -->
        <div class="header-section">
          <div class="tabs-container">
            <div v-for="(tab, index) in tabs" :key="index" class="tab-item"
              :class="{ active: videoStatus === tab.value }" @click="changeStatus(tab.value)">
              {{ tab.label }}
            </div>
          </div>
          <div class="toolbar">
            <div class="manual-audit-filter">
              <el-checkbox v-model="onlyNeedManualAudit" @change="reloadVideos">仅显示需要人工审核</el-checkbox>
            </div>
            <el-tooltip content="如果看不到待审核内容，请点击刷新按钮" placement="bottom">
              <div class="refresh-btn" @click="reloadVideos">
                <el-icon class="refresh-icon">
                  <Refresh />
                </el-icon>
                <span>刷新</span>
              </div>
            </el-tooltip>
            <div class="total-count">共 {{ total }} 条</div>
          </div>
        </div>

        <!-- 视频列表 -->
        <div class="table-container" v-loading="loading">
          <el-table :data="videos" style="width: 100%" :row-class-name="tableRowClassName"
            :header-cell-style="{ background: '#f5f7fa', color: '#606266', fontWeight: '600' }">
            <template #empty>
              <div class="empty-state">
                <img src="~assets/img/silly.png" alt="没有数据" class="empty-image">
                <p class="empty-text">没有找到任何数据</p>
              </div>
            </template>
            <el-table-column label="VID" min-width="90" align="left">
              <template #default="scope">
                <span class="video-id"># {{ scope.row.video.vid }}</span>
              </template>
            </el-table-column>

            <el-table-column label="封面" min-width="176" align="center">
              <template #default="scope">
                <div class="cover-wrapper">
                  <el-image :src="scope.row.video.coverUrl" fit="cover" class="video-cover"
                    :preview-src-list="[scope.row.video.coverUrl]" :initial-index="0" preview-teleported loading="lazy">
                    <template #error>
                      <div class="image-error">
                        <el-icon>
                          <Picture />
                        </el-icon>
                      </div>
                    </template>
                    <template #placeholder>
                      <div class="image-placeholder">
                        <el-icon class="is-loading">
                          <Loading />
                        </el-icon>
                        <span>加载中...</span>
                      </div>
                    </template>
                  </el-image>
                  <div class="cover-actions">
                    <el-button type="primary" size="small" circle @click.stop="previewImage(scope.row.video.coverUrl)"
                      class="preview-btn">
                      <el-icon>
                        <ZoomIn />
                      </el-icon>
                    </el-button>
                  </div>
                </div>
              </template>
            </el-table-column>

            <el-table-column label="标题" min-width="200" show-overflow-tooltip>
              <template #default="scope">
                <div class="video-title">{{ scope.row.video.title }}</div>
              </template>
            </el-table-column>

            <el-table-column label="投稿用户" min-width="120">
              <template #default="scope">
                <el-button type="text" class="user-name" @click="handleUserClick(scope.row.user)">
                  {{ scope.row.user.nickname }}
                </el-button>
              </template>
            </el-table-column>

            <el-table-column label="分区" min-width="180">
              <template #default="scope">
                <div class="category-tags">
                  <el-tag size="small" effect="plain" class="primary-category">
                    {{ scope.row.category.mcName }}
                  </el-tag>
                  <el-icon>
                    <ArrowRight />
                  </el-icon>
                  <el-tag size="small" effect="plain" class="secondary-category">
                    {{ scope.row.category.scName }}
                  </el-tag>
                </div>
              </template>
            </el-table-column>

            <el-table-column label="投稿时间" min-width="150">
              <template #default="scope">
                <div class="upload-time">
                  <!-- <el-icon>
                    <Calendar />
                  </el-icon> -->
                  <span class="upload-date-text">{{ formatDateDisplay(scope.row.video.uploadDate) }}</span>
                </div>
              </template>
            </el-table-column>

            <el-table-column label="状态" min-width="120">
              <template #default="scope">
                <div class="status-display">
                  <el-tag :type="getStatusTagType(scope.row.video.status)" effect="light" round>
                    <el-icon class="status-icon">
                      <component :is="getStatusIcon(scope.row.video.status)"></component>
                    </el-icon>
                    <span>{{ getStatusText(scope.row.video.status) }}</span>
                  </el-tag>
                </div>
              </template>
            </el-table-column>

            <el-table-column label="审核情况" min-width="120">
              <template #default="scope">
                <div class="audit-status" v-if="scope.row.auditStatus !== undefined">
                  <el-tag :type="getAuditTagType(scope.row.auditStatus)" size="small" effect="light" round>
                    {{ getAuditStatusText(scope.row.auditStatus) }}
                  </el-tag>
                </div>
              </template>
            </el-table-column>

            <el-table-column fixed="right" min-width="100" align="center">
              <template #default="scope">
                <el-button type="primary" size="small" plain round class="detail-btn" @click="openNewPage({
                  name: 'videoDetail',
                  params: { vid: scope.row.video.vid }
                })">
                  详情
                  <el-icon class="el-icon--right">
                    <ArrowRight />
                  </el-icon>
                </el-button>
              </template>
            </el-table-column>
          </el-table>
        </div>

        <!-- 分页器 -->
        <div class="pagination-container">
          <el-pagination background layout="total, prev, pager, next, jumper" :total="total" :page-size="10"
            :pager-count="pagerCount" :current-page="page" @current-change="pageChange">
          </el-pagination>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
export default {
  name: "VideoReview",

  data() {
    return {
      videoStatus: 0,                 // 要查询的视频状态，0 正在审核，1 通过审核，2 打回整改
      videos: [],                     // 视频列表数据
      page: 1,                        // 当前页码
      total: 100,                     // 总条数
      pagerCount: 7,                  // 分页器按钮数量
      loading: true,                  // 加载状态
      onlyNeedManualAudit: false,     // 只显示需要人工审核的视频
      tabs: [
        { label: '待审核', value: 0 },
        { label: '已过审', value: 1 },
        { label: '未过审', value: 2 }
      ]
    }
  },

  methods: {
    // 请求类方法
    // 查询视频数量
    async getTotal() {
      try {
        let params = {
          vstatus: this.videoStatus,
        };

        if (this.onlyNeedManualAudit) {
          params.needManualReview = true;
        }

        const res = await this.$get('/review/video/total', {
          params: params,
          headers: {
            Authorization: "Bearer " + localStorage.getItem("teri_token"),
          },
        });

        console.log("获取视频总数:", res.data);

        if (res.data && res.data.data !== undefined) {
          this.total = res.data.data;
        } else {
          console.error("获取视频总数失败:", res.data);
          this.total = 0;
          this.videos = [];
        }
      } catch (err) {
        console.error("获取视频总数异常:", err);
        this.total = 0;
        this.videos = [];
      }
    },

    // 查询当前页的视频
    async getVideos() {
      try {
        let params = {
          vstatus: this.videoStatus,
          page: this.page,
          quantity: 10,
        };

        if (this.onlyNeedManualAudit) {
          params.needManualReview = true;
        }

        console.log("请求参数:", params);

        const res = await this.$get('/review/video/getpage', {
          params: params,
          headers: {
            Authorization: "Bearer " + localStorage.getItem("teri_token"),
          },
        });

        console.log("获取视频列表:", res.data);

        if (res.data.data) {
          // 增强视频对象，添加审核状态信息
          this.videos = res.data.data;

          // 获取每个视频的审核状态
          for (let i = 0; i < this.videos.length; i++) {
            await this.getVideoAuditStatus(this.videos[i]);
          }
        } else {
          console.error("获取视频列表失败:", res.data);
          this.videos = [];
        }
        console.log("处理后的视频列表: ", this.videos);
      } catch (err) {
        console.error("获取视频列表异常:", err);
        this.videos = [];
      }
    },

    // 获取视频的审核状态
    async getVideoAuditStatus(videoItem) {
      try {
        const res = await this.$get(`/admin/audit/video/${videoItem.video.vid}`, {
          headers: {
            Authorization: "Bearer " + localStorage.getItem("teri_token"),
          },
        });

        console.log(`视频${videoItem.video.vid}审核状态:`, res.data);

        if (res.data && res.data.data) {
          const video = res.data.data.video || {};
          const auditResults = res.data.data.auditResults || [];

          // 优先从视频对象中获取审核状态
          if (video.textAuditStatus !== undefined ||
            video.imageAuditStatus !== undefined ||
            video.videoAuditStatus !== undefined) {

            console.log(`视频${videoItem.video.vid}审核状态字段:`, {
              text: video.textAuditStatus,
              image: video.imageAuditStatus,
              video: video.videoAuditStatus
            });

            // 设置审核状态，确保使用数字比较
            // 0：全部通过或待审核，1：部分需要人工审核，2：部分违规，3：审核处理中
            const statuses = [
              Number(video.textAuditStatus),
              Number(video.imageAuditStatus),
              Number(video.videoAuditStatus)
            ].filter(s => !isNaN(s)); // 过滤掉非数字值

            const hasViolation = statuses.some(status => status === 3 || status === 5);
            const needManualReview = statuses.some(status => status === 2);
            const hasProcessing = statuses.some(status => status === 0);

            if (hasViolation) {
              videoItem.auditStatus = 2; // 存在违规
            } else if (needManualReview) {
              videoItem.auditStatus = 1; // 需人工审核
            } else if (hasProcessing) {
              videoItem.auditStatus = 3; // 审核处理中
            } else {
              videoItem.auditStatus = 0; // 自动审核通过
            }

          } else if (auditResults.length > 0) {
            // 使用审核结果数组计算状态
            console.log(`视频${videoItem.video.vid}使用审核结果计算状态:`, auditResults);

            // 设置审核状态，确保使用数字比较
            const statuses = auditResults.map(r => Number(r.status)).filter(s => !isNaN(s));
            const hasViolation = statuses.some(status => status === 3 || status === 5);
            const needManualReview = statuses.some(status => status === 2);
            const hasProcessing = statuses.some(status => status === 0);

            if (hasViolation) {
              videoItem.auditStatus = 2; // 存在违规
            } else if (needManualReview) {
              videoItem.auditStatus = 1; // 需人工审核
            } else if (hasProcessing) {
              videoItem.auditStatus = 3; // 审核处理中
            } else {
              videoItem.auditStatus = 0; // AI自动审核通过
            }
          } else {
            videoItem.auditStatus = 0;
          }

          // 添加审核类型统计
          videoItem.auditTypes = {
            text: auditResults.find(r => Number(r.type) === 1),
            image: auditResults.find(r => Number(r.type) === 2),
            video: auditResults.find(r => Number(r.type) === 3)
          };
        } else {
          console.warn(`获取视频${videoItem.video.vid}审核状态失败:`, res.data);
          videoItem.auditStatus = 0;
        }
      } catch (error) {
        console.error("获取视频审核状态失败:", error);
        videoItem.auditStatus = 0;
      }
    },

    // 格式化日期显示
    formatDateDisplay(dateStr) {
      if (!dateStr) return '';
      // 如果日期格式已经是统一的，则直接返回
      // 否则可以进行格式化处理
      return dateStr;
    },

    // 获取审核状态文本
    getAuditStatusText(status) {
      const statusMap = {
        0: 'AI自动审核通过',
        1: '需人工审核',
        2: '存在违规',
        3: '审核处理中'
      };
      return statusMap[status] || '未知状态';
    },

    // 获取审核状态标签类型
    getAuditTagType(status) {
      const typeMap = {
        0: 'success',
        1: 'warning',
        2: 'danger',
        3: 'info'
      };
      return typeMap[status] || '';
    },

    // 获取视频状态标签类型
    getStatusTagType(status) {
      const typeMap = {
        0: 'warning',
        1: 'success',
        2: 'danger'
      };
      return typeMap[status] || 'info';
    },

    // 获取视频状态图标
    getStatusIcon(status) {
      const iconMap = {
        0: 'Loading',
        1: 'CircleCheckFilled',
        2: 'CircleCloseFilled'
      };
      return iconMap[status] || 'InfoFilled';
    },

    // 获取视频状态文本
    getStatusText(status) {
      const statusMap = {
        0: '待审核',
        1: '已通过',
        2: '未通过'
      };
      return statusMap[status] || '未知状态';
    },

    // 表格行样式
    tableRowClassName() {
      return '';
    },

    // 处理用户点击
    handleUserClick(user) {
      // 可以在这里添加用户详情的跳转
      console.log('用户点击:', user);
    },

    // 事件处理方法
    // 切换审核类型
    changeStatus(vstatus) {
      this.videoStatus = vstatus;
      if (this.page !== 1) {
        this.page = 1;  // 这里页码改变会触发重加载
      } else {
        this.reloadVideos();
      }
    },

    // 改变页码时的回调
    async pageChange(page) {
      this.page = page;
      await this.reloadVideos();
    },

    // 重新加载视频列表
    async reloadVideos() {
      this.loading = true;
      await this.getTotal();
      if (this.total > 0) {
        await this.getVideos();
      } else {
        this.videos = [];
      }
      this.loading = false;
    },

    // 判断是否小窗
    changeWidth() {
      if (window.innerWidth < 768) {
        this.pagerCount = 3;
      } else if (window.innerWidth < 992) {
        this.pagerCount = 5;
      } else {
        this.pagerCount = 7;
      }
    },

    // 打开新标签页
    openNewPage(route) {
      window.open(this.$router.resolve(route).href, '_blank');
    },

    // 预览图片
    previewImage(url) {
      if (!url) return;
      // 创建大图预览窗口
      const imgWindow = window.open('', '_blank');
      imgWindow.document.write(`
        <!DOCTYPE html>
        <html>
          <head>
            <title>封面预览</title>
            <style>
              body {
                margin: 0;
                padding: 0;
                display: flex;
                justify-content: center;
                align-items: center;
                min-height: 100vh;
                background-color: #1a1a1a;
                overflow: hidden;
              }
              .preview-container {
                max-width: 90vw;
                max-height: 90vh;
                position: relative;
              }
              img {
                max-width: 100%;
                max-height: 90vh;
                display: block;
                object-fit: contain;
                border-radius: 4px;
                box-shadow: 0 4px 20px rgba(0,0,0,0.2);
              }
              .close-btn {
                position: absolute;
                top: 20px;
                right: 20px;
                background-color: rgba(0,0,0,0.6);
                color: white;
                border: none;
                border-radius: 50%;
                width: 40px;
                height: 40px;
                font-size: 20px;
                cursor: pointer;
                display: flex;
                align-items: center;
                justify-content: center;
                transition: all 0.3s;
              }
              .close-btn:hover {
                background-color: rgba(255,255,255,0.2);
                transform: scale(1.1);
              }
              .loading {
                color: white;
                font-size: 18px;
                font-family: Arial, sans-serif;
              }
            </style>
          </head>
          <body>
            <div class="loading">加载中...</div>
            <div class="preview-container">
              <img src="${url}" onload="document.querySelector('.loading').style.display = 'none';">
              <button class="close-btn" onclick="window.close()">×</button>
            </div>
          </body>
        </html>
      `);
    },
  },

  // 生命周期钩子
  async created() {
    this.changeWidth();
    await this.getTotal();
    if (this.total > 0) {
      await this.getVideos();
    }
    this.loading = false;
  },

  mounted() {
    // 监听窗口大小变化，判断是否小窗
    window.addEventListener('resize', this.changeWidth);
  },

  unmounted() {
    window.removeEventListener('resize', this.changeWidth);
  },
}
</script>

<style scoped>
/* 全局容器 */
.video-review-container {
  width: 100%;
  min-height: 100%;
  padding: 16px;
}

.content-wrapper {
  max-width: 100%;
  margin: 0 auto;
}

.review-card {
  background-color: #fff;
  border-radius: 12px;
  box-shadow: 0 4px 20px rgba(0, 0, 0, 0.08);
  overflow: hidden;
  height: calc(100vh - 96px);
  display: flex;
  flex-direction: column;
}

/* 顶部导航和工具栏 */
.header-section {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 0 24px;
  height: 64px;
  border-bottom: 1px solid #ebeef5;
  background-color: #fff;
  flex-shrink: 0;
}

.tabs-container {
  display: flex;
  height: 100%;
}

.tab-item {
  position: relative;
  padding: 0 20px;
  display: flex;
  align-items: center;
  font-size: 16px;
  color: #606266;
  cursor: pointer;
  transition: all 0.3s;
  height: 100%;
}

.tab-item:hover {
  color: var(--brand_pink, #ff6699);
}

.tab-item.active {
  color: var(--brand_pink, #ff6699);
  font-weight: 600;
}

.tab-item.active::after {
  content: '';
  position: absolute;
  bottom: 0;
  left: 0;
  width: 100%;
  height: 3px;
  background-color: var(--brand_pink, #ff6699);
  border-radius: 3px 3px 0 0;
}

.toolbar {
  display: flex;
  align-items: center;
  gap: 16px;
}

.manual-audit-filter {
  margin-right: 8px;
}

.refresh-btn {
  display: flex;
  align-items: center;
  gap: 4px;
  cursor: pointer;
  color: var(--brand_blue, #409eff);
  padding: 6px 12px;
  border-radius: 4px;
  transition: all 0.2s ease;
}

.refresh-btn:hover {
  background-color: rgba(64, 158, 255, 0.1);
}

.refresh-icon {
  font-size: 16px;
}

.total-count {
  font-size: 14px;
  color: #606266;
}

/* 表格容器 */
.table-container {
  flex: 1;
  overflow-y: auto;
  padding: 0 24px;
}

/* 表格内部样式 */
.video-id {
  font-family: monospace;
  font-weight: 600;
  color: #909399;
}

.cover-wrapper {
  width: 160px;
  height: 90px;
  margin: 0 auto;
  border-radius: 8px;
  overflow: hidden;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
  position: relative;
}

.video-cover {
  width: 100%;
  height: 100%;
  object-fit: cover;
  transition: transform 0.3s;
}

.cover-wrapper:hover .video-cover {
  transform: scale(1.05);
}

.cover-actions {
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  display: flex;
  justify-content: center;
  align-items: center;
  background-color: rgba(0, 0, 0, 0.5);
  opacity: 0;
  transition: opacity 0.3s ease;
}

.cover-wrapper:hover .cover-actions {
  opacity: 1;
}

.preview-btn {
  background-color: var(--el-color-primary);
  color: white;
  transform: scale(0.9);
  transition: all 0.3s;
}

.preview-btn:hover {
  transform: scale(1);
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.2);
}

.image-error {
  width: 100%;
  height: 100%;
  display: flex;
  align-items: center;
  justify-content: center;
  background-color: #f5f7fa;
  color: #909399;
  font-size: 24px;
}

.image-placeholder {
  width: 100%;
  height: 100%;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  background-color: #f5f7fa;
  color: #909399;
  font-size: 14px;
  gap: 8px;
}

.video-title {
  font-weight: 500;
  font-size: 14px;
  color: #303133;
}

.user-name {
  font-weight: 500;
}

.user-name:hover {
  color: var(--brand_pink, #ff6699);
}

.category-tags {
  display: flex;
  align-items: center;
  gap: 8px;
}

.primary-category {
  background-color: rgba(255, 184, 0, 0.1);
  color: #FFB800;
  border-color: #FFB800;
}

.secondary-category {
  background-color: rgba(0, 176, 255, 0.1);
  color: #00B0FF;
  border-color: #00B0FF;
}

.upload-time {
  display: flex;
  align-items: center;
  gap: 6px;
  color: #606266;
  font-size: 14px;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}

.upload-date-text {
  white-space: nowrap;
}

.status-display {
  display: flex;
  align-items: center;
}

.status-icon {
  margin-right: 4px;
  vertical-align: middle;
}

.audit-status {
  display: flex;
  align-items: center;
}

.detail-btn {
  transition: all 0.3s;
  font-size: 13px;
}

.detail-btn:hover {
  transform: translateX(3px);
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

/* 分页容器 */
.pagination-container {
  padding: 16px 0;
  display: flex;
  justify-content: center;
  background-color: #fff;
  border-top: 1px solid #ebeef5;
  flex-shrink: 0;
}

/* 空状态样式 */
.empty-state {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 40px 0;
}

.empty-image {
  width: 120px;
  height: 120px;
  margin-bottom: 15px;
}

.empty-text {
  font-size: 14px;
  color: #909399;
}

/* 响应式适配 */
@media (max-width: 1200px) {
  .header-section {
    flex-direction: column;
    height: auto;
    padding: 12px 24px;
  }

  .tabs-container {
    width: 100%;
    justify-content: space-around;
    margin-bottom: 12px;
  }

  .toolbar {
    width: 100%;
    justify-content: space-between;
  }
}

@media (max-width: 768px) {
  .video-review-container {
    padding: 8px;
  }

  .review-card {
    border-radius: 8px;
  }

  .header-section {
    padding: 12px;
  }

  .tab-item {
    padding: 0 10px;
    font-size: 14px;
  }

  .toolbar {
    flex-wrap: wrap;
    gap: 8px;
  }

  .manual-audit-filter,
  .refresh-btn,
  .total-count {
    font-size: 13px;
  }

  .table-container {
    padding: 0 12px;
  }

  .cover-wrapper {
    width: 120px;
    height: 68px;
  }
}

/* 动画效果 */
@keyframes spin {
  0% {
    transform: rotate(0deg);
  }

  100% {
    transform: rotate(360deg);
  }
}

.refresh-btn:active .refresh-icon {
  animation: spin 1s linear;
}
</style>